//
//  RootView.m
//  Photograph
//
//  Created by TravelRound on 15/11/17.
//  Copyright © 2015年 TravelRound. All rights reserved.
//

#import "PhotoView.h"
#import "SubScrollView.h"

@interface PhotoView () <UIScrollViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollV;
@property (nonatomic, retain) UIPageControl *pageC;
@property (nonatomic, assign) NSInteger prePage;

@end

@implementation PhotoView

- (void)dealloc
{
    [_scrollV release];
    [_pageC release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.prePage = 1;
        [self createSubviews];
    }
    return self;
}

- (void)createSubviews
{
    
    self.backgroundColor = [UIColor whiteColor];
    
    self.scrollV = [[UIScrollView alloc] initWithFrame:self.frame];
    self.scrollV.contentSize = CGSizeMake(self.frame.size.width * 21, 0);
    self.scrollV.contentOffset = CGPointMake(self.frame.size.width, 0);
    self.scrollV.pagingEnabled = YES;
    self.scrollV.delegate = self;
    [self addSubview:self.scrollV];
    [_scrollV release];
    
    for (NSInteger i = 0; i < 21; i++) {
        
        SubScrollView *subScrollV = [[SubScrollView alloc] initWithFrame:CGRectMake(self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height) index:i];
        [self.scrollV addSubview:subScrollV];
        [subScrollV release];
        
    }
    
    self.pageC = [[UIPageControl alloc] initWithFrame:CGRectMake(50, 600, self.frame.size.width - 100, 30)];
    self.pageC.numberOfPages = 19;
    [self.pageC addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:self.pageC];
    [_pageC release];
    
}

- (void)pageAction:(UIPageControl *)sender
{
    
    self.scrollV.contentOffset = CGPointMake(self.scrollV.frame.size.width * (sender.currentPage + 1), 0);
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    // 若是大scrollView才进行处理
    if (self.scrollV == scrollView) {
        
        // 获取当前页码
        NSInteger currentPage = self.scrollV.contentOffset.x / self.scrollV.frame.size.width;
        
        // 为了循环滑动
        if (0 == currentPage) {
            
            self.scrollV.contentOffset = CGPointMake(self.scrollV.frame.size.width * 19, 0);
            currentPage = 19;
            
        } else if (20 == currentPage) {
            
            self.scrollV.contentOffset = CGPointMake(self.scrollV.frame.size.width * 1, 0);
            currentPage = 1;
            
        }
        
        // 判断当前页码与上一页码是否相等
        if (currentPage != self.prePage) {
            
            [[self.scrollV.subviews objectAtIndex:self.prePage] setZoomScale:1];
            
            self.pageC.currentPage = currentPage - 1;
            
            // 更新之前页码
            self.prePage = currentPage;
            
        }
        
    }
    
}

@end
